/*
 * @Author: soso
 * @Date: 2022-03-09 16:46:07
 * @LastEditTime: 2022-03-09 16:58:36
 * @LastEditors: Please set LastEditors
 * @Description: 获取工作路径
 * @FilePath: /go-utils/utils/path.go
 */
package utils

import (
	"log"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"
)

// 当前执行文件目录
func GetCurrentAbPath() string {
	dir := getCurrentAbPathByExecutable()
	tmpDir, _ := filepath.EvalSymlinks(os.TempDir())
	if strings.Contains(dir, tmpDir) {
		return getCurrentAbPathByCaller()
	}
	// 使用air情况下的处理
	if strings.HasSuffix(dir, "/tmp") {
		dir = filepath.Dir(dir)
	}
	return dir
}

// 获取当前执行文件绝对路径
func getCurrentAbPathByExecutable() string {
	exePath, err := os.Executable()
	if err != nil {
		log.Fatal(err)
	}
	res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
	return res
}

// 获取当前执行文件绝对路径（go run）
func getCurrentAbPathByCaller() string {
	var abPath string
	_, filename, _, ok := runtime.Caller(0)
	if ok {
		abPath = path.Dir(filename)
	}
	return abPath
}

// 执行文件所在目录
func ExecDir() (execdir string) {
	execdir, _ = os.Executable()
	// air 环境下返回工作目录
	if strings.HasSuffix(execdir, "/tmp/main") {
		execdir = GetCurrentAbPath()
	} else {
		execdir = filepath.Dir(execdir)
	}
	return
}
